import Reflux from 'reflux';
import {Control} from 'react-keeper';
import Actions from './Actions';
import DB from '../../../../app/db';
import update from 'react-addons-update';
import StorageUtils from "../../../../app/storage";

import {Toast, Modal} from 'antd-mobile';

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    userInfo: {},
    subjectId: '',
    subject: {},
    questionnaire: {},
    isLoading: true,
    isVoteCountLoading: true,
    result: {
      voteCount: 0
    }
  },

  customInit(subjectId) {
    this.data.isLoading = true;
    this.data.isVoteCountLoading = true;
    this.data.userInfo = update(this.data.userInfo, {$merge: {...StorageUtils.getUser()}});
    this.data.subjectId = subjectId;
    this.updateComponent();
    this.isVoted();
    this.initQuestionnaire(subjectId);
  },

  initQuestionnaire(subjectId) {
    let t = this;
    DB.vote.questionnaire({subjectId: subjectId}).then(
      function (content) {
        if (content && content.id !== null) {
          let questionnaire = t.data.questionnaire;
          t.data.questionnaire = {
            ...questionnaire,
            ...content
          };
          t.updateComponent();
          t.initAnswer();
          t.data.isLoading = false;
          t.updateComponent();
          t.initVoteRatio();
        }
      },
      function (error) {
        console.log(error);
      }
    );
  },

  isVoted() {
    let t = this;
    DB.vote.isVoted({
      subjectId: t.data.subjectId,
      voterId: StorageUtils.getStorageItem('proprietor').id
    }).then(
      function (content) {
        t.data.questionnaire = update(t.data.questionnaire, {
          isVoted: {$set: content}
        });
        t.updateComponent();
        DB.vote.voteCount({subjectId: t.data.subjectId}).then(
          function (content) {
            t.data.result = update(t.data.result, {
              voteCount: {$set: content}
            });
            t.data.isVoteCountLoading = false;
            t.updateComponent();
          },
          function (error) {
            console.log(error);
          }
        );
      },
      function (error) {
        console.log(error);
      }
    );
  },

  initAnswer() {
    let t = this;
    let questions = t.data.questionnaire.questions;
    questions.map(q=>{
      q.options.map(o=>{
        DB.vote.answerByQuestionId({
          questionId: q.id,
          voterId: StorageUtils.getStorageItem('proprietor').id
        }).then(
          function (content) {
            if (content && content.length > 0) {
              let answers = content;
              t.data.questionnaire = update(t.data.questionnaire, {
                questions: {$apply: questions => {
                  return questions.map(q=>{
                    if (q.id === answers[0].questionId) {
                      return update(q, {
                        options: {$apply: options => {
                          return options.map(o=>{
                            let isSelected = false;
                            answers.map(a=> {
                              if (a.answer === o.id) {
                                isSelected = true;
                              }
                            });
                            return update(o, {
                              isSelected: {$set: isSelected}
                            });
                          });
                        }}
                      });
                    } else {
                      return q;
                    }
                  })
                }}
              });
              t.updateComponent();
            }
          },
          function (error) {
            console.log(error);
          }
        );
      })
    });
  },

  onAnswerChange(options, questionId) {
    let t = this;
    t.data.questionnaire = update(t.data.questionnaire, {
      questions: {$apply: questions => {
        return questions.map(q=>{
          if (q.id === questionId) {
            return update(q, {
              options: {$set: options}
            });
          } else {
            return q;
          }
        })
      }}
    });
    t.updateComponent();
  },

  submitAnswer() {
    let t = this;
    let subjectId = t.data.questionnaire.id;
    let answers = [];
    let allVoted = true;
    t.data.questionnaire.questions.map(q=>{
      let isVoted = false;
      q.options.map(o=>{
        if (o.isSelected) {
          isVoted = true;
          answers.push({
            subjectId: subjectId,
            questionId: q.id,
            answer: o.id,
            voterId: StorageUtils.getStorageItem('proprietor').id
          })
        }
      });
      if (!isVoted) {
        allVoted = false;
      }
    });
    if (allVoted) {
      Modal.alert('确认', '确定提交问卷？', [
        {
          text: '提交',
          onPress: () => {
            DB.vote.saveAnswer({answer: JSON.stringify(answers)}).then(
              function (content) {
                if (content) {
                  Control.go('/home/vote');
                } else {
                  Toast.fail('提交问卷失败！')
                }
              },
              function (error) {
                console.log(error);
                Toast.fail('提交问卷失败！')
              }
            );
          },
          style: 'default'
        },
        {
          text: '取消',
          onPress: () => {},
          style: 'default'
        }
      ]);
    } else {
      Toast.fail('您有问题未作答！')
    }
  },

  // 调查结果比例
  initVoteRatio() {
    let t = this;
    let questions = t.data.questionnaire.questions;
    questions.map(question=>{
      question.options.map(option=>{
        DB.vote.voteCountOption({optionId: option.id}).then(
          function (content) {
            t.data.questionnaire = update(t.data.questionnaire, {
              questions: {$apply: questions => {
                return questions.map(q=>{
                  if (q.id === question.id) {
                    return update(q, {
                      options: {$apply: options => {
                        return options.map(o=>{
                          if (o.id === option.id) {
                            return update(o, {
                              voteCount: {$set: content}
                            });
                          } else {
                            return o;
                          }
                        });
                      }}
                    });
                  } else {
                    return q;
                  }
                })
              }}
            });
            t.updateComponent();
          },
          function (error) {

          }
        );
      })
    })
  },

  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState: function () {
    return this.data;
  }
});
